//
//  SortViewController.m
//  MeiTuan
//
//  Created by Ansen on 15-3-14.
//  Copyright (c) 2015年 Ansen. All rights reserved.
//

#import "SortViewController.h"
#import "MetaTool.h"
#import "Sort.h"
#import "UIView+Extension.h"
#import "Const.h"

@interface SortButton : UIButton

@property (nonatomic, strong) Sort *sort;

@end

@implementation SortButton

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        
        [self setBackgroundImage:[UIImage imageNamed:@"btn_filter_normal"] forState:UIControlStateNormal];
        [self setBackgroundImage:[UIImage imageNamed:@"btn_filter_selected"] forState:UIControlStateHighlighted];
    }
    return self;
}

-(void)setSort:(Sort *)sort
{
    _sort = sort;
    [self setTitle:sort.label forState:UIControlStateNormal];
}

@end

@interface SortViewController ()

@end

@implementation SortViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSArray *sorts = [MetaTool sorts];
    NSUInteger count = sorts.count;
    CGFloat btnW = 100;
    CGFloat btnH = 30;
    CGFloat btnX = 15;
    CGFloat btnStartY = 15;
    CGFloat btnMargin = 15;
    CGFloat height = 0;
    for (NSInteger i=0; i < count; i++) {
        
        SortButton *btn = [[SortButton alloc] init];
        btn.sort = sorts[i];
        btn.width = btnW;
        btn.height = btnH;
        btn.x = btnX;
        btn.y = btnStartY + (btnMargin + btnH)*i;
        [btn addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
        
        height = CGRectGetMaxY(btn.frame);
    }
    
    // 设置控制器在popover中的尺寸
    CGFloat width = btnMargin * 2 + btnW;
    height += btnMargin;
    self.preferredContentSize = CGSizeMake(width, height);
    
}
- (void)buttonClick:(SortButton *)button
{
    [NotificationCenter postNotificationName:SortDidChangeNotification object:nil userInfo:@{SelectSort : button.sort}];
}

@end
